package com.yoomiito.app.ui.my.maintain;

import android.content.Intent;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.jakewharton.rxbinding3.view.RxView;
import com.yoomiito.app.Constant;
import com.yoomiito.app.R;
import com.yoomiito.app.adapter.MaintainAdapter;
import com.yoomiito.app.address.AddressListActivity;
import com.yoomiito.app.base.App;
import com.yoomiito.app.base.BaseActivity;
import com.yoomiito.app.model.bean.AddressInfo;
import com.yoomiito.app.model.bean.AppInterfaceInfo;
import com.yoomiito.app.model.bean.GoodsDetail;
import com.yoomiito.app.model.bean.GoodsList;
import com.yoomiito.app.model.bean.MaintainGoods;
import com.yoomiito.app.ui.anyview.order.ShowAddressView;
import com.yoomiito.app.ui.my.car.ShopCarActivity;
import com.yoomiito.app.ui.my.instrument.InstrumentActivity;
import com.yoomiito.app.ui.order.list.OrderActivity;
import com.yoomiito.app.ui.order.sureorder.BuyResultActivity;
import com.yoomiito.app.ui.order.sureorder.singleGoods.BuyGoodsActivity;
import com.yoomiito.app.utils.AllCode;
import com.yoomiito.app.utils.AllUtils;
import com.yoomiito.app.utils.Const;
import com.yoomiito.app.utils.EventMessage;
import com.yoomiito.app.utils.L;
import com.yoomiito.app.utils.SpannableUtils;
import com.yoomiito.app.utils.TouchUtils;
import com.yoomiito.app.utils.UserInfoConfig;
import com.yoomiito.app.utils.YMToast;
import com.yoomiito.app.widget.dialog.AlipayH5Dialog;
import com.yoomiito.app.widget.dialog.PayDialog;
import com.yoomiito.app.widget.dialog.PickDialog;
import com.yoomiito.app.widget.state.ContentType;
import com.yoomiito.app.widget.state.EmptyType;
import com.yoomiito.app.widget.state.LoadingType;
import com.yoomiito.app.widget.state.StatusManager;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;


public class MaintainActivity extends BaseActivity<MaintainPresenter> {


    @BindView(R.id.rv_goods)
    RecyclerView recyclerView;
    @BindView(R.id.ll_empty)
    LinearLayout llEmpty;
    @BindView(R.id.tv_desc)
    TextView tvDesc;
    @BindView(R.id.btn_pick)
    Button mBuyBtn;
    @BindView(R.id.act_buy_goods_money)
    TextView mPayPriceTv;
    @BindView(R.id.address_container)
    FrameLayout addressParentView;
    private AddressInfo mAddressInfo;
    private String eventId = "";
    private PickDialog dialog;
    private MaintainAdapter mAdapter;
    private PayDialog payDialog;
    public String pay_type;//支付类型
    private MaintainGoods data;
    private String mGoodsTotalPrice = "0";
    private int mGoodsSize = 0;
    AppInterfaceInfo appInterfaceInfo;
    private ShowAddressView mShowAddressView;

    List<GoodsList> lists = new ArrayList<>();
    @Override
    public View getLayoutView() {
        mStatusManager = new StatusManager.Builder(context)
                .addType(new ContentType(R.layout.act_maintain))
                .addType(new LoadingType())
                .addType(new EmptyType().setEmptyContent("无复购商品"))
                .build();
        return mStatusManager.view();
    }

    @Override
    public int getLayoutId() {
        return 0;
    }

    @Override
    public MaintainPresenter newP() {
        return new MaintainPresenter(App.mAppConfig);
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        mAdapter = new MaintainAdapter();
        recyclerView.setAdapter(mAdapter);
        String s = "共" + mGoodsSize + "件 合计¥" + mGoodsTotalPrice;
        int p = s.indexOf("¥");
        SpannableString spanText = SpannableUtils.getSizeAndPriceText(s, R.color.color_FF035B, p, s.length(), p, p + 1);
        mPayPriceTv.setText(spanText);
        mAdapter.setOnGoods(new MaintainAdapter.OnClick() {
            @Override
            public void onGetGood(String goods) {
                lists.clear();
                mGoodsTotalPrice = "0";//总价
                mGoodsSize = 0;
                for (int i = 0; i < mAdapter.getData().size(); i++) {
                    if (mAdapter.getData().get(i).setNum > 0) {
                        GoodsList goodsDetail = new GoodsList();
                        goodsDetail.num = mAdapter.getData().get(i).setNum;
                        goodsDetail.productName = mAdapter.getData().get(i).getTitle();
                        goodsDetail.unit = mAdapter.getData().get(i).unit;
                        goodsDetail.productId = mAdapter.getData().get(i).productId;
                        String goodsTotalPrice = AllUtils.priceMul_2(mAdapter.getData().get(i).getSalePrice(), goodsDetail.num);
                        lists.add(goodsDetail);
                        mGoodsTotalPrice =  AllUtils.priceSum_2(goodsTotalPrice,mGoodsTotalPrice);
                        mGoodsSize +=  goodsDetail.num;
                    }
                }
                String s = "共" + mGoodsSize + "件 合计¥" + mGoodsTotalPrice;
                int p = s.indexOf("¥");
                SpannableString spanText = SpannableUtils.getSizeAndPriceText(s, R.color.color_FF035B, p, s.length(), p, p + 1);
                mPayPriceTv.setText(spanText);

            }
        });
        getP().confirmOrder();
        RxView.clicks(mBuyBtn)
                .throttleFirst(1, TimeUnit.SECONDS)
                .subscribe(unit -> {
                    if (mGoodsSize == 0) {
                        YMToast.showText("请选择购买的商品");
                        return;
                    }
                    showPayDialog();
                });
    }


    @OnClick({R.id.act_buy_goods_back, R.id.btn_pick})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.act_buy_goods_back:
                finish();
                break;
        }
    }

    public void showAddressView(AddressInfo addressInfo) {
        if (appInterfaceInfo.address == 1) {
            addressParentView.setVisibility(View.VISIBLE);
        } else {
            addressParentView.setVisibility(View.GONE);
        }
        dismissLoading();
        mShowAddressView = new ShowAddressView(this);
        addressParentView.addView(mShowAddressView);
        mAddressInfo = addressInfo;
        if (mAddressInfo != null && mAddressInfo.getId() != null) {
            mShowAddressView.setAddressInfo(mAddressInfo);
            mShowAddressView.showAddress();
        }
    }


    public void showPayDialog() {
        dismissLoading();
        if(AllUtils.moneyCompare1(appInterfaceInfo.buyMoneyMin,mGoodsTotalPrice)){
            YMToast.showText("单笔购买金额不能小于"+appInterfaceInfo.buyMoneyMin+"元");
            return;
        }
        if (payDialog == null) {
            payDialog = new PayDialog(this);
            payDialog.setOnResultListener((moneyPay, wxPay, aliPay, offline,quick, dismiss) -> {
                if (dismiss) {
                    return;
                }
                if (moneyPay == 0 && wxPay == 0 && aliPay == 0 && offline == 0  && quick == 0) {
                    YMToast.showText("请选择付款通道");
                    return;
                }
                if(moneyPay == 1 && wxPay == 0 && aliPay == 0 && AllUtils.moneyCompare1(mGoodsTotalPrice,data.userAccount)){
                    YMToast.showText("您的余额不足够本次支付!");
                    return;
                }
                payDialog.dismiss();
                showLoading();
                int payType = 0;
                if (moneyPay == 1 && wxPay == 0 && aliPay == 0 && offline == 0 && quick == 0) {
                    payType = 3;
                } else {
                    if (wxPay == 1) {
                        payType = 1;
                    }
                    if (aliPay == 1) {
                        payType = 2;
                    }
                    if (offline == 1) {
                        payType = 5;
                    }
                    if (wxPay == 1 && moneyPay == 1) {
                        payType = 7;
                    }
                    if (aliPay == 1 && moneyPay == 1) {
                        payType = 6;
                    }
                    if (quick == 1){
                        payType = 8;
                    }
                }
                createOrder(payType);

                //付款方式1-微信，2-支付宝，3-余额支付，5-线下支付,6-支付宝+余额，7-微信+余额
//                if (moneyPay == 1 && wxPay == 0 && aliPay == 0) {
//                    //余额支付 需要密码框
//                    if (UserInfoConfig.havePayPsw()) {
//                        showPsw();
//                    } else {
//                        showSetPswDialog();
//                    }
//                } else {
//                    //非余额支付
//
////
////                    getP().pay(mPayOrderId, wxPay, aliPay, moneyPay == 1 ? mBalance : "0",
////                            mGoodsType == Type.GoodsType.GiveMore ? (mGoodsDetail.getProduct_type() + 1) : mGoodsDetail.getProduct_type(),
////                            "", yoMoneyPay);
//                }

            });
        }
        L.i("支付总价：" + mGoodsTotalPrice);
        payDialog.setBalance(data.userAccount);
        payDialog.setShow(appInterfaceInfo);
        payDialog.setPayMoney("¥" + mGoodsTotalPrice);
        payDialog.setRadio(AllUtils.moneyCompare(data.userAccount, mGoodsTotalPrice));
        payDialog.show();
    }

    private boolean show = false;
    public void setShow(){
        show = true;
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(show){
            findViewById(R.id.act_buy_goods_ll).post(new Runnable() {
                public void run() {
                    AlipayH5Dialog accountCancelDialog = new AlipayH5Dialog(MaintainActivity.this, new AlipayH5Dialog.OnCloseListener() {
                        @Override
                        public void confirm() {
//                            RouterUtils.toMain(BuyGoodsActivity.this, 4);
                            Intent intent = new Intent(MaintainActivity.this, OrderActivity.class);
                            intent.putExtra("type", 1);
                            startActivity(intent);
                            finish();

                        }
                    });
                    accountCancelDialog.show();
                }
            });
            show = false;
        }
    }

    @Override
    public void eventMessage(EventMessage eventMessage) {
        super.eventMessage(eventMessage);
        if (Constant.PAY_RESULT.equals(eventMessage.getEventType())) {
            payResult(eventMessage);
        }
    }


    private void createOrder(int payType) {
        List<GoodsList> lists = new ArrayList<>();
        for (int i = 0; i < mAdapter.getData().size(); i++) {
            if (mAdapter.getData().get(i).setNum > 0) {
                GoodsList goodsDetail = new GoodsList();
                goodsDetail.productId =mAdapter.getData().get(i).productId;
                goodsDetail.num = mAdapter.getData().get(i).setNum;
                lists.add(goodsDetail);
            }
        }
        String note = "";
        getP().getInterface(data.appInterface,  mAddressInfo.getUserName(),  mAddressInfo.getProvinceName(),
                mAddressInfo.getCityName(),  mAddressInfo.getCountyName(), mAddressInfo.getProvinceName() +
                        mAddressInfo.getCityName() + mAddressInfo.getCountyName(),  mAddressInfo.getMobile(),  mAddressInfo.getAddress(),
                note, 1, appInterfaceInfo.address, appInterfaceInfo.type, payType, new Gson().toJson(lists));
    }

    public void setData(MaintainGoods data) {
        appInterfaceInfo = new AppInterfaceInfo();
        appInterfaceInfo.wxPay = data.wxPay;
        appInterfaceInfo.zfbPay = data.zfbPay;
        appInterfaceInfo.offline = data.offline;
        appInterfaceInfo.fastPay = data.fastPay;
        appInterfaceInfo.online = 1;
        appInterfaceInfo.type = data.type;
        appInterfaceInfo.blendPay = data.blendPay;
        appInterfaceInfo.nickname = data.nickname;
        appInterfaceInfo.mobile = data.mobile;
        appInterfaceInfo.address = data.address;
        appInterfaceInfo.buyMoneyMin = data.buyMoneyMin;
        this.data = data;
        tvDesc.setText(data.pickMsg);
        List<GoodsDetail> list = new ArrayList<>();
        list.addAll(data.data);
        list.addAll(data.data1);
        mAdapter.setNewData(list);
        getP().getAddress();
    }

    public void payResult(EventMessage eventMessage) {
        dismissLoading();
        if ("wxpay".equals(pay_type)) {
            TouchUtils.onBuyEvent(eventId,
                    UserInfoConfig.getRoleId(),
                    UserInfoConfig.getAgent(),
                    AllCode.Fail == eventMessage.getCode() ? "wx_pay_fail" : "wx_pay_success");
        }
        BuyResultActivity.Companion.start(MaintainActivity.this, eventMessage);
        finish();
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (Const.RequestCode.AddressCode == requestCode && data != null) {
            mAddressInfo = (AddressInfo) data.getSerializableExtra(Constant.DATA);
            L.i("地址：" + mAddressInfo.toString());
            mShowAddressView.setAddressInfo(mAddressInfo);
            mShowAddressView.showAddress();
//            getP().getAddress();
        }
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
